
package com.itheima.aop;

import com.itheima.domain.dto.LoginDTO;
import com.itheima.domain.pojo.EmpLoginLog;
import com.itheima.domain.vo.LoginVO;
import com.itheima.domain.vo.Result;
import com.itheima.mapper.LogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;


/**
 * @author: Sch
 * @Date: 2025/07/18 19:57
 * @Description:
 */

@Slf4j
@Aspect
@Component
public class EmpLoginLogAspect {
    @Autowired
    private LogMapper logMapper;

    @Around("execution(* com.itheima.controller.LoginController.login(..))")
    public Result emplog(ProceedingJoinPoint pjp) throws Throwable {
        EmpLoginLog empLoginLog = new EmpLoginLog();

/**
         * 将用户名,密码和操作时间添加到日志对象
         */

        LoginDTO args = (LoginDTO) pjp.getArgs()[0];
        String password = args.getPassword();
        String username = args.getUsername();
        LocalDateTime now = LocalDateTime.now();
        empLoginLog.setPassword(password);
        empLoginLog.setUsername(username);
        empLoginLog.setLoginTime(now);


        long start = System.currentTimeMillis();
        try {
            Result proceed =(Result) pjp.proceed();
            LoginVO data = (LoginVO) proceed.getData();
            String token = data.getToken();
            empLoginLog.setJwt(token);
            empLoginLog.setIsSuccess((short) 1);
            long end = System.currentTimeMillis();
            long costTime = end - start;
            empLoginLog.setCostTime(costTime);
            return proceed;
        } catch (Exception e) {
            empLoginLog.setIsSuccess((short) 0);
            long end = System.currentTimeMillis();
            long costTime = end - start;
            empLoginLog.setCostTime(costTime);
            throw e;
        } finally {
            logMapper.insert(empLoginLog);
        }

    }

}

